﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace evepctlib
{
	public class OreChartManager
	{
		private readonly string _xml;
		private readonly Dictionary<string, List<double>> _prices;
		private int _jour = DateTime.Today.Day;
		private int _mois = DateTime.Today.Month;
		private int _annee = DateTime.Today.Year;
		private DateTime _today = DateTime.Today;
		private DateTime _histoDate = DateTime.Today;
		
		public OreChartManager()
		{
			// Mise à jour de histoDate, date de départ de l'historique des graphs (3 mois)
			_histoDate = _histoDate - TimeSpan.FromDays(89);
			
			// Création du dossier de l'application
			var appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
			var evepctDirectory = appData + @"\evepct";
			var evepctXmlDirectory = evepctDirectory + @"\xml\";

			if (!Directory.Exists(evepctDirectory)) Directory.CreateDirectory(evepctDirectory);
			if (!Directory.Exists(evepctXmlDirectory)) Directory.CreateDirectory(evepctXmlDirectory);

			_xml = evepctXmlDirectory + "evepctcharts.xml";
			string _oldXml = evepctXmlDirectory + "evepctcharts_old.xml";

			
			if (File.Exists(_xml))
			{
				try
				{
					File.Delete(_oldXml);
					File.Move(_xml, _oldXml);
				}
				catch (Exception)
				{
					MessageBox.Show(
						"Erreur critique : Impossible de supprimer le fichier evepctcharts.xml ou evepctcharts_old.xml. Il est possible qu'il soit accédé par un autre programme (ce qui semble peu probable). Veuillez arrêter tous les processus de l'application et tenter de le redémarrer. Sinon, vous pouvez également tenter de redémarrer votre ordinateur.",
						"Erreur Critique", MessageBoxButtons.OK, MessageBoxIcon.Error);
					Application.Exit();
				}
				
				
			}
			
			if (!File.Exists(_xml))
			{
				// Region The Citadel : &region_ids=10000033
				// Min quantity 1000 : &min_quantity=1000
				// var httpReader = new HttpReader("http://eve-metrics.com/api/history.xml?type_ids=1230,1228,1224,18,1227,20,1226,1231,21,1229,1232,19,1225,1223,22,11396&days=15");
				try
				{
					var httpReader = new HttpReader("http://pct.camak.fr/files/evepctcharts.xml");
					var chaineXml = httpReader.Read();
					if (chaineXml.Length > 0)
						File.AppendAllText(_xml, chaineXml);
					else
						throw new Exception();
				}
				catch (Exception)
				{
					if (File.Exists(_oldXml))
					{
						File.Move(_oldXml, _xml);
						MessageBox.Show(
							"Les valeurs affichées ne sont pas à jour et ne pourrons être considérées comme bonne pour la vente à la corporation.\n\nImpossible d'accéder au serveur.", "Erreur mise à jour", MessageBoxButtons.OK, MessageBoxIcon.Warning);
					}
					else
					{
						MessageBox.Show(
							"Impossible de charger les données de vente.\n\nImpossible d'accéder au serveur.",
							"Erreur mise à jour", MessageBoxButtons.OK, MessageBoxIcon.Error);
						Application.Exit();
					}
				}
			}

			_prices = new Dictionary<string, List<double>>();

			_prices.Add("Veldspar", new List<double>());
			_prices.Add("Scordite", new List<double>());
			_prices.Add("Pyroxeres", new List<double>());
			_prices.Add("Plagioclase", new List<double>());
			_prices.Add("Omber", new List<double>());
			_prices.Add("Kernite", new List<double>());
			_prices.Add("Jaspet", new List<double>());
			_prices.Add("Hemorphite", new List<double>());
			_prices.Add("Hedbergite", new List<double>());
			_prices.Add("Gneiss", new List<double>());
			_prices.Add("Dark Ochre", new List<double>());
			_prices.Add("Spodumain", new List<double>());
			_prices.Add("Crokite", new List<double>());
			_prices.Add("Bistot", new List<double>());
			_prices.Add("Arkonor", new List<double>());
			_prices.Add("Mercoxit", new List<double>());
			
		}

		public Dictionary<string, List<double>> Read()
		{
			var ds = new DataSet();
			ds.ReadXml(_xml);

			var veldsparXml = ds.Tables["Veldspar"].AsEnumerable();
			var scorditeXml = ds.Tables["Scordite"].AsEnumerable();
			var pyroxeresXml = ds.Tables["Pyroxeres"].AsEnumerable();
			var plagioclaseXml = ds.Tables["Plagioclase"].AsEnumerable();
			var omberXml = ds.Tables["Omber"].AsEnumerable();
			var kerniteXml = ds.Tables["Kernite"].AsEnumerable();
			var jaspetXml = ds.Tables["Jaspet"].AsEnumerable();
			var hemorphiteXml = ds.Tables["Hemorphite"].AsEnumerable();
			var hedbergiteXml = ds.Tables["Hedbergite"].AsEnumerable();
			var gneissXml = ds.Tables["Gneiss"].AsEnumerable();
			var darkOchreXml = ds.Tables["Dark_Ochre"].AsEnumerable();
			var spodumainXml = ds.Tables["Spodumain"].AsEnumerable();
			var crokiteXml = ds.Tables["Crokite"].AsEnumerable();
			var bistotXml = ds.Tables["Bistot"].AsEnumerable();
			var arkonorXml = ds.Tables["Arkonor"].AsEnumerable();
			var mercoxitXml = ds.Tables["Mercoxit"].AsEnumerable();


			var veldspar =	from ve in veldsparXml
							select new
			               			{
										date = Convert.ToDateTime(ve["date"]),
										prix = Convert.ToDouble(ve["price"])
			               			};

			var scordite = from ve in scorditeXml
						   select new
						   {
							   date = Convert.ToDateTime(ve["date"]),
							   prix = Convert.ToDouble(ve["price"])
						   };

			var pyroxeres = from ve in pyroxeresXml
						   select new
						   {
							   date = Convert.ToDateTime(ve["date"]),
							   prix = Convert.ToDouble(ve["price"])
						   };

			var plagioclase = from ve in plagioclaseXml
						   select new
						   {
							   date = Convert.ToDateTime(ve["date"]),
							   prix = Convert.ToDouble(ve["price"])
						   };

			var omber = from ve in omberXml
						   select new
						   {
							   date = Convert.ToDateTime(ve["date"]),
							   prix = Convert.ToDouble(ve["price"])
						   };

			var kernite = from ve in kerniteXml
						   select new
						   {
							   date = Convert.ToDateTime(ve["date"]),
							   prix = Convert.ToDouble(ve["price"])
						   };

			var jaspet = from ve in jaspetXml
						   select new
						   {
							   date = Convert.ToDateTime(ve["date"]),
							   prix = Convert.ToDouble(ve["price"])
						   };

			var hemorphite = from ve in hemorphiteXml
						   select new
						   {
							   date = Convert.ToDateTime(ve["date"]),
							   prix = Convert.ToDouble(ve["price"])
						   };

			var hedbergite = from ve in hedbergiteXml
						   select new
						   {
							   date = Convert.ToDateTime(ve["date"]),
							   prix = Convert.ToDouble(ve["price"])
						   };

			var gneiss = from ve in gneissXml
						   select new
						   {
							   date = Convert.ToDateTime(ve["date"]),
							   prix = Convert.ToDouble(ve["price"])
						   };

			var darkOchre = from ve in darkOchreXml
						   select new
						   {
							   date = Convert.ToDateTime(ve["date"]),
							   prix = Convert.ToDouble(ve["price"])
						   };

			var spodumain = from ve in spodumainXml
						   select new
						   {
							   date = Convert.ToDateTime(ve["date"]),
							   prix = Convert.ToDouble(ve["price"])
						   };

			var crokite = from ve in crokiteXml
						   select new
						   {
							   date = Convert.ToDateTime(ve["date"]),
							   prix = Convert.ToDouble(ve["price"])
						   };

			var bistot = from ve in bistotXml
						   select new
						   {
							   date = Convert.ToDateTime(ve["date"]),
							   prix = Convert.ToDouble(ve["price"])
						   };

			var arkonor = from ve in arkonorXml
						   select new
						   {
							   date = Convert.ToDateTime(ve["date"]),
							   prix = Convert.ToDouble(ve["price"])
						   };

			var mercoxit = from ve in mercoxitXml
						   select new
						   {
							   date = Convert.ToDateTime(ve["date"]),
							   prix = Convert.ToDouble(ve["price"])
						   };

			// Pour chaque jour depuis le jour historique
			// on ajoute une valeur dans les listes de minerai en fonction de la date la plus proche
			for (var d = _histoDate; d <= _today; d = d + TimeSpan.FromDays(1))
			{
				var prixVeldspar = from r in veldspar
				                   where r.date == ((from t in veldspar
				                                     where t.date <= d
				                                     select t).Max(t => t.date))
				                   select r.prix;
				_prices["Veldspar"].Add(prixVeldspar.First());



				var prixScordite = from r in scordite
				                   where r.date == ((from t in scordite
				                                     where t.date <= d
				                                     select t).Max(t => t.date))
				                   select r.prix;
				_prices["Scordite"].Add(prixScordite.First());



				var prixPyroxeres = from r in pyroxeres
				                    where r.date == ((from t in pyroxeres
				                                      where t.date <= d
				                                      select t).Max(t => t.date))
				                    select r.prix;
				_prices["Pyroxeres"].Add(prixPyroxeres.First());



				var prixPlagioclase = from r in plagioclase
				                      where r.date == ((from t in plagioclase
				                                        where t.date <= d
				                                        select t).Max(t => t.date))
				                      select r.prix;
				_prices["Plagioclase"].Add(prixPlagioclase.First());



				var prixOmber = from r in omber
				                where r.date == ((from t in omber
				                                  where t.date <= d
				                                  select t).Max(t => t.date))
				                select r.prix;
				_prices["Omber"].Add(prixOmber.First());



				var prixKernite = from r in kernite
								  where r.date == ((from t in kernite
				                                     where t.date <= d
				                                     select t).Max(t => t.date))
				                   select r.prix;
				_prices["Kernite"].Add(prixKernite.First());



				var prixJaspet = from r in jaspet
								 where r.date == ((from t in jaspet
				                                     where t.date <= d
				                                     select t).Max(t => t.date))
				                   select r.prix;
				_prices["Jaspet"].Add(prixJaspet.First());



				var prixHemorphite = from r in hemorphite
									 where r.date == ((from t in hemorphite
				                                     where t.date <= d
				                                     select t).Max(t => t.date))
				                   select r.prix;
				_prices["Hemorphite"].Add(prixHemorphite.First());



				var prixHedbergite = from r in hedbergite
									 where r.date == ((from t in hedbergite
				                                     where t.date <= d
				                                     select t).Max(t => t.date))
				                   select r.prix;
				_prices["Hedbergite"].Add(prixHedbergite.First());



				var prixGneiss = from r in gneiss
								 where r.date == ((from t in gneiss
				                                     where t.date <= d
				                                     select t).Max(t => t.date))
				                   select r.prix;
				_prices["Gneiss"].Add(prixGneiss.First());



				var prixDarkOchre = from r in darkOchre
									where r.date == ((from t in darkOchre
				                                     where t.date <= d
				                                     select t).Max(t => t.date))
				                   select r.prix;
				_prices["Dark Ochre"].Add(prixDarkOchre.First());



				var prixSpodumain = from r in spodumain
									where r.date == ((from t in spodumain
				                                     where t.date <= d
				                                     select t).Max(t => t.date))
				                   select r.prix;
				_prices["Spodumain"].Add(prixSpodumain.First());



				var prixCrokite = from r in crokite
								  where r.date == ((from t in crokite
				                                     where t.date <= d
				                                     select t).Max(t => t.date))
				                   select r.prix;
				_prices["Crokite"].Add(prixCrokite.First());



				var prixBistot = from r in bistot
								 where r.date == ((from t in bistot
				                                     where t.date <= d
				                                     select t).Max(t => t.date))
				                   select r.prix;
				_prices["Bistot"].Add(prixBistot.First());



				var prixArkonor = from r in arkonor
								  where r.date == ((from t in arkonor
				                                     where t.date <= d
				                                     select t).Max(t => t.date))
				                   select r.prix;
				_prices["Arkonor"].Add(prixArkonor.First());



				var prixMercoxit = from r in mercoxit
								   where r.date == ((from t in mercoxit
				                                     where t.date <= d
				                                     select t).Max(t => t.date))
				                   select r.prix;
				_prices["Mercoxit"].Add(prixMercoxit.First());

			}
			
			return _prices;
			
		}
		

	}


	public enum Mineral
	{
		Veldspar,
		Scordite,
		Pyroxeres,
		Plagioclase,
		Omber,
		Kernite,
		Jaspet,
		Hemorphite,
		Hedbergite,
		Gneiss,
		DarkOchre,
		Spodumain,
		Crokite,
		Bistot,
		Arkonor,
		Mercoxit,
	}
}



